package com.example.coursehub.classmanagement.service.impl;

import com.example.coursehub.classmanagement.entity.Class;
import com.example.coursehub.classmanagement.entity.StudentClass;
import com.example.coursehub.classmanagement.repository.ClassRepository;
import com.example.coursehub.classmanagement.repository.StudentClassRepository;
import com.example.coursehub.classmanagement.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 班级管理服务实现类
 */
@Service
@Transactional
public class ClassServiceImpl implements ClassService {
    
    @Autowired
    private ClassRepository classRepository;
    
    @Autowired
    private StudentClassRepository studentClassRepository;
    
    // 班级相关操作
    @Override
    public Class createClass(Class clazz) {
        return classRepository.save(clazz);
    }
    
    @Override
    public Class updateClass(Long id, Class clazz) {
        Optional<Class> existingClass = classRepository.findById(id);
        if (existingClass.isPresent()) {
            Class updatedClass = existingClass.get();
            updatedClass.setName(clazz.getName());
            updatedClass.setDescription(clazz.getDescription());
            updatedClass.setMaxStudents(clazz.getMaxStudents());
            return classRepository.save(updatedClass);
        }
        throw new RuntimeException("班级不存在，ID: " + id);
    }
    
    @Override
    public void deleteClass(Long id) {
        if (classRepository.existsById(id)) {
            // 删除相关的学生班级关联
            studentClassRepository.deleteByClassId(id);
            classRepository.deleteById(id);
        } else {
            throw new RuntimeException("班级不存在，ID: " + id);
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<Class> getClassById(Long id) {
        return classRepository.findById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Class> getAllClasses() {
        return classRepository.findAll();
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Class> getClassesByCourse(Long courseId) {
        return classRepository.findByCourseId(courseId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Class> getClassesByTeacher(Long teacherId) {
        return classRepository.findByTeacherId(teacherId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Class> searchClassesByName(String name) {
        return classRepository.findByNameContaining(name);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Class> getAvailableClasses() {
        return classRepository.findAvailableClasses();
    }
    
    // 学生班级关联操作
    @Override
    public StudentClass joinClass(Long studentId, Long classId) {
        // 检查学生是否已经加入班级
        if (isStudentInClass(studentId, classId)) {
            throw new RuntimeException("学生已经加入该班级");
        }
        
        // 检查班级是否还有空位
        Optional<Class> clazz = classRepository.findById(classId);
        if (clazz.isPresent()) {
            Class currentClass = clazz.get();
            if (currentClass.getCurrentStudents() >= currentClass.getMaxStudents()) {
                throw new RuntimeException("班级已满，无法加入");
            }
            
            // 创建学生班级关联
            StudentClass studentClass = new StudentClass(studentId, classId);
            StudentClass savedStudentClass = studentClassRepository.save(studentClass);
            
            // 更新班级当前学生数
            currentClass.setCurrentStudents(currentClass.getCurrentStudents() + 1);
            classRepository.save(currentClass);
            
            return savedStudentClass;
        } else {
            throw new RuntimeException("班级不存在，ID: " + classId);
        }
    }
    
    @Override
    public void leaveClass(Long studentId, Long classId) {
        Optional<StudentClass> studentClass = studentClassRepository.findByStudentIdAndClassId(studentId, classId);
        if (studentClass.isPresent()) {
            StudentClass sc = studentClass.get();
            sc.setStatus(StudentClass.StudentStatus.DROPPED);
            studentClassRepository.save(sc);
            
            // 更新班级当前学生数
            Optional<Class> clazz = classRepository.findById(classId);
            if (clazz.isPresent()) {
                Class currentClass = clazz.get();
                currentClass.setCurrentStudents(Math.max(0, currentClass.getCurrentStudents() - 1));
                classRepository.save(currentClass);
            }
        } else {
            throw new RuntimeException("学生未加入该班级");
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<StudentClass> getStudentsByClass(Long classId) {
        return studentClassRepository.findByClassIdAndStatus(classId, StudentClass.StudentStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<StudentClass> getClassesByStudent(Long studentId) {
        return studentClassRepository.findByStudentIdAndStatus(studentId, StudentClass.StudentStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isStudentInClass(Long studentId, Long classId) {
        return studentClassRepository.existsByStudentIdAndClassIdAndStatus(
            studentId, classId, StudentClass.StudentStatus.ACTIVE);
    }
    
    // 统计相关操作
    @Override
    @Transactional(readOnly = true)
    public long getActiveStudentCount(Long classId) {
        return studentClassRepository.countByClassIdAndStatus(classId, StudentClass.StudentStatus.ACTIVE);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getClassCountByTeacher(Long teacherId) {
        return classRepository.countByTeacherId(teacherId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getClassCountByCourse(Long courseId) {
        return classRepository.countByCourseId(courseId);
    }
}